package com.lzy.web;

import com.lzy.po.Comment;
import com.lzy.po.User;
import com.lzy.service.BlogService;
import com.lzy.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @autor shkstart
 * @create 2021-01-07 14:56)
 */
@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";  //返回blog页面的commentList块
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session){
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));

        //判断管理员是否登录
        User user = (User) session.getAttribute("user");
        if(user != null){
            comment.setAvatar(user.getAvatar()); //使用管理员自己的头像
            //comment.setNickname(user.getNickname()); //管理员使用自己的昵称
            comment.setAdminComment(true);
        }else{
            comment.setAvatar(avatar);  //游客使用默认的头像
            comment.setAdminComment(false);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/"+blogId;

    }
}
